package com.kangyi.admin.service.Impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.kangyi.admin.mapper.*;
import com.kangyi.admin.service.NursingHomeAccountService;
import com.kangyi.constant.MessageConstant;
import com.kangyi.context.BaseContext;
import com.kangyi.dto.BulkOperationDTO;
import com.kangyi.dto.EditNursingHomeAccountDTO;
import com.kangyi.dto.NursingHomeAccountPageQueryDTO;
import com.kangyi.entity.AdminUser;
import com.kangyi.entity.GuestsStaying;
import com.kangyi.entity.NursingHomeReview;
import com.kangyi.exception.AccountException;
import com.kangyi.exception.PermissionsException;
import com.kangyi.result.NursingHomeAccountPageResult;
import com.kangyi.vo.AdminUserVO;
import com.kangyi.vo.DetailNursingHomeAccountVO;
import com.kangyi.vo.NursingHomeAccountPageQueryVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.kafka.KafkaProperties;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author Blank
 * @version 1.0
 */
@Service
public class NursingHomeAccountServiceImpl implements NursingHomeAccountService {

    @Autowired
    private AdminUserMapper adminUserMapper;

    @Autowired
    private ReviewReplyMapper reviewReplyMapper;

    @Autowired
    private GuestsStayingMapper guestsStayingMapper;

    @Autowired
    private ReviewMapper reviewMapper;

    @Autowired
    private ReviewImageMapper reviewImageMapper;

    @Autowired
    private NursingHomeBookingMapper nursingHomeBookingMapper;

    @Autowired
    private NursingHomeFavoriteMapper nursingHomeFavoriteMapper;

    @Autowired
    private NursingHomeTagMapper nursingHomeTagMapper;

    @Autowired
    private NursingHomeEventMapper nursingHomeEventMapper;

    @Autowired
    private NursingHomeServiceMapper nursingHomeServiceMapper;

    @Autowired
    private FeeMapper feeMapper;

    @Autowired
    private NursingHomeRequirementMapper nursingHomeRequirementMapper;

    @Autowired
    private NursingHomeMapper nursingHomeMapper;

    //调用后检查当前线程id是否有足够的权限进行后续操作
    public void validateUserPermissions() {
        Integer currentId = BaseContext.getCurrentId();
        AdminUserVO adminUserVO = adminUserMapper.selectById(currentId);
        if (!adminUserVO.getPermissions().equals(1)) {
            throw new PermissionsException(MessageConstant.INSUFFICIENT_PRIVILEGE);
        }
    }

    @Override
    public NursingHomeAccountPageResult pageQuery(NursingHomeAccountPageQueryDTO nursingHomeAccountPageQueryDTO) {
        validateUserPermissions();
        PageHelper.startPage(nursingHomeAccountPageQueryDTO.getPage(),nursingHomeAccountPageQueryDTO.getPageSize());
        Page<NursingHomeAccountPageQueryVO> page = adminUserMapper.NursingHomeAccountPageQuery(nursingHomeAccountPageQueryDTO);
        long total = page.getTotal();
        List<NursingHomeAccountPageQueryVO> result = page.getResult();
        int enable = 0;
        int disable = 0;
        for (NursingHomeAccountPageQueryVO vo : result) {
            if (vo.getStatus() == 1) {
                enable++;
            } else if (vo.getStatus() == 2) {
                disable++;
            }
        }
        return new NursingHomeAccountPageResult(total,result,enable,disable);
    }

    @Override
    public void bulkOperation(BulkOperationDTO bulkOperationDTO) {
        validateUserPermissions();
        for (Integer id : bulkOperationDTO.getIds()) {
            if (id.equals(1)) {
                throw new AccountException(MessageConstant.UNABLE_TO_OPERATE_SUPER_ADMINISTRATOR_ACCOUNT);
            }
            AdminUser build = AdminUser.builder()
                    .id(id)
                    .status(bulkOperationDTO.getType())
                    .build();
            adminUserMapper.bulkOperation(build);
        }
    }

    @Override
    @Transactional
    public void deleteManageAccount(List<Integer> ids) {
        for (Integer id : ids) {
            validateUserPermissions(); // 每次删除前都进行权限验证
            if (id.equals(1)) {
                throw new AccountException(MessageConstant.UNABLE_TO_OPERATE_SUPER_ADMINISTRATOR_ACCOUNT);
            }
            AdminUserVO adminUserVO = adminUserMapper.selectById(id);
            if (adminUserVO.getPosition() == 2) {
                Integer currentId = BaseContext.getCurrentId();
                if (!currentId.equals(1)) {
                    throw new AccountException(MessageConstant.NO_PERMISSION_OPERATION);
                }
                Integer nursingHomeId = adminUserVO.getNursingHomeId();
                // 删除院长相关联的数据
                // 将院长养老院下的员工包含院长所绑定的养老院id设为null
                List<AdminUser> adminUserList = adminUserMapper.getByNursingHomeId(nursingHomeId);
                if (adminUserList != null) {
                    for (AdminUser adminUser : adminUserList) {
                        adminUserMapper.updateNursingHomeId(adminUser.getId());
                    }
                }

                // 设置入住人员的养老院id为null
                List<GuestsStaying> guestsStayingList = guestsStayingMapper.getByNursingHomeId(nursingHomeId);
                if (guestsStayingList != null) {
                    for (GuestsStaying guestsStaying : guestsStayingList) {
                        guestsStayingMapper.updateNursingHomeIdIsNull(guestsStaying.getId());
                    }
                }
                // 清空养老院下的评论、评论图片、评论回复
                // 查询养老院下有哪些评论
                List<NursingHomeReview> nursingHomeReviewList = reviewMapper.getByNursingHomeId(nursingHomeId);
                if (nursingHomeReviewList != null) {
                    for (NursingHomeReview nursingHomeReview : nursingHomeReviewList) {
                        // 删除所有回复
                        reviewReplyMapper.deleteById(nursingHomeReview.getId());
                        // 删除所有评论图片
                        reviewImageMapper.deleteById(nursingHomeReview.getId());
                    }
                }
                // 删除所有评论
                reviewMapper.deleteByNursingHomeId(nursingHomeId);
                // 清空预约记录
                nursingHomeBookingMapper.deleteByNursingHomeId(nursingHomeId);
                // 清空收藏记录
                nursingHomeFavoriteMapper.deleteByNursingHomeId(nursingHomeId);
                // 清空所有养老院信息
                // 清空标签表
                nursingHomeTagMapper.delete(nursingHomeId);
                // 清空精彩活动表
                nursingHomeEventMapper.deleteNursingHomeId(nursingHomeId);
                // 清空特色服务表
                nursingHomeServiceMapper.deleteByNursingHomeId(nursingHomeId);
                // 清空收费表
                feeMapper.deleteByNursingHomeId(nursingHomeId);
                // 清空入住条件表
                nursingHomeRequirementMapper.deleteByNursingHomeId(nursingHomeId);
                // 清空养老院基本表
                nursingHomeMapper.deleteByNursingHomeId(nursingHomeId);
                // 删除用户
                adminUserMapper.deleteById(id);
                continue; // 跳过后续的重复删除操作
            }
            try {
                adminUserMapper.updateNursingHome(id);
                // 删除回复
                reviewReplyMapper.deleteByAdminUserId(id);
                adminUserMapper.deleteById(id);
            } catch (Exception e) {
                // 处理数据库操作异常，给用户明确的错误信息
                throw new AccountException("删除账户时出现异常：" + e.getMessage());
            }
        }
    }

    @Override
    public DetailNursingHomeAccountVO detailAccount(Integer id) {
        validateUserPermissions();
        DetailNursingHomeAccountVO DetailNursingHomeAccountVO = adminUserMapper.detailAccount(id);
        if (DetailNursingHomeAccountVO == null) {
            throw new AccountException(MessageConstant.DATA_NOT_EXIST);
        }
        return DetailNursingHomeAccountVO;
    }

    @Override
    public void editAccount(EditNursingHomeAccountDTO editNursingHomeAccountDTO) {
        validateUserPermissions();
        AdminUser adminUser = new AdminUser();
        BeanUtils.copyProperties(editNursingHomeAccountDTO, adminUser);
        adminUserMapper.update(adminUser);
    }
}
